﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MINERP.DAL;
using MINERP.MODEL.FoundationModel;
using MINERP.COM;

namespace MINERP.BLL.InnerReturn
{
    public class InnerReturnBLL2
    {
        //newSampleYPDBEntities dataBase = new newSampleYPDBEntities();
        public PhotoView GetPhotoViewByBarCode(string inBarCode, out string strErrMessage)
        {
            using (newSampleYPDBEntities dataBase = new newSampleYPDBEntities())
            {

                BLL.InnerReturn.PhotoView photoView = new PhotoView();
                int printed = (int)PhotoStatus.Printed;
                int fenpian = (int)PhotoStatus.FenPian;
                photoInfo info =
                    dataBase.photoInfo.Where(
                        p => p.PhotoBarCode == inBarCode).FirstOrDefault
                        ();
                if (!(info.status == printed || info.status == fenpian))
                {
                    strErrMessage="当前照片未打印或者产品不在生产中，当前照片状态为" + info.status;
                    return null;
                }
                photoView.Photo = new PhotoInfo_Info()
                                      {
                                          Height = info.Height,
                                          Width = info.Width,
                                          PhotoBarCode = info.PhotoBarCode,
                                          PhotoId = info.photoId,
                                          PhotoName = info.photoName,
                                          PicPath = info.picPath
                                      };
                if (!info.orderInfoReference.IsLoaded)
                {
                    info.orderInfoReference.Load();
                }
                orderInfo product = info.orderInfo;
                if (!info.orderInfo.WorkOrderFlowList.IsLoaded)
                {
                    info.orderInfo.WorkOrderFlowList.Load();
                }
                List<WorkOrderFlowList> flowList = info.orderInfo.WorkOrderFlowList.OrderBy(p => p.WorkOrder).ToList();
                photoView.Product = new OrderInfo_Info()
                                        {
                                            OrderProductCode = product.OrderProductCode,
                                            OrderProductId = product.OrderProductId,
                                            OrderProductName = product.OrderProductName
                                        };
                List<FlowView> listFlow = new List<FlowView>();
                foreach (WorkOrderFlowList flow in flowList)
                {
                    FlowView view = new FlowView();
                    if (!flow.tb_TechReference.IsLoaded)
                    {
                        flow.tb_TechReference.Load();
                    }
                    if (flow.tb_Tech.TechType == (int)TechType.system)
                    {
                        continue;
                    }
                    
                    Tb_Tech_Info tech = new Tb_Tech_Info()
                                            {
                                                TechId = flow.tb_Tech.TechId,
                                                TechName = flow.tb_Tech.TechName,
                                                TechType = flow.tb_Tech.TechType
                                            };
                    view.Flow = new WorkOrderFlowList_Info()
                                    {
                                        WorkFlowListId = flow.WorkFlowListId,
                                        TechId = flow.tb_Tech.TechId,
                                        UserId = flow.UserId,
                                        WorkOrder = flow.WorkOrder
                                    };
                    users user = dataBase.users.FirstOrDefault(p => p.userID == view.Flow.UserId);
                    if (user != null)
                    {
                        view.UserName = user.UserName;
                    }
                    if (flow.Status == (int)OrderFlowListStatus.Useable)
                    {
                        photoView.TechFrom = tech;

                    }
                    if (flow.tb_Tech.TechType == (int)TechType.print)
                    {
                        continue;
                    }
                    view.Tech = tech;
                    listFlow.Add(view);
                }
                if (photoView.TechFrom == null)
                {
                    strErrMessage = "该产品未找到正在生产的流程节点";
                    return null;
                }
                photoView.ListFlow = listFlow;
                strErrMessage = "";
                return photoView;
            }
        }
        /// <summary>
        /// 取到所有的用户列表
        /// </summary>
        /// <returns></returns>
        public List<User_Info> GetAllUsers()
        {
            using (newSampleYPDBEntities dataBase = new newSampleYPDBEntities())
            {

                List<users> userList = dataBase.users.Where(p => p.IsUseful).ToList();
                List<User_Info> infos = new List<User_Info>();
                foreach (users user in userList)
                {
                    User_Info info = new User_Info();
                    info = new User_Info() { UserID = user.userID, UserName = user.UserName };
                    infos.Add(info);
                }
                return infos.OrderBy(p => p.UserName).ToList();
            }
        }
        /// <summary>
        /// 取到所有节点名称
        /// </summary>
        /// <returns></returns>
        public List<Tb_Tech_Info> GetAllTech()
        {
            int intSystech = (int)TechType.system;
            using (newSampleYPDBEntities dataBase = new newSampleYPDBEntities())
            {


                List<tb_Tech> techs = dataBase.tb_Tech.Where(p => p.TechType != intSystech).ToList();
                List<Tb_Tech_Info> infos = new List<Tb_Tech_Info>();
                foreach (tb_Tech list in techs)
                {
                    Tb_Tech_Info info = new Tb_Tech_Info() { TechId = list.TechId, TechName = list.TechName };

                    ////福州屏蔽输出管理
                    //if (info.TechName.Equals("输出管理"))
                    //{
                    //    continue;
                    //}
                    infos.Add(info);
                }
                return infos;
            }
        }
        public List<string> GetAllPaperWasteType()
        {
            using (newSampleYPDBEntities dataBase = new newSampleYPDBEntities())
            {


                List<string> PaperWasteTypeList = new List<string>();

                List<PaperWasteType> userList = dataBase.PaperWasteType.ToList();
                foreach (PaperWasteType list in userList)
                {
                    PaperWasteTypeList.Add(list.PaperOperationTypeName);
                }

                return PaperWasteTypeList;
            }
        }
        /// <summary>
        /// 创建反单
        /// </summary>
        /// <param name="inPhotoList">照片列表</param>
        /// <param name="inReturnUserId">返工对象员工</param>
        /// <param name="CreateUserId">创建人</param>
        /// <param name="inRemark">返工原因</param>
        /// <param name="ReturnTechTo">返工到流程</param>
        public List<PhotoView> CreateInnerReturn(List<PhotoView> inPhotoList, int inReturnUserId, int inCreateUserId, string inRemark, int inReturnTechTo)
        {
            using (newSampleYPDBEntities dataBase = new newSampleYPDBEntities())
            {

                List<PhotoView> unSuccessList = new List<PhotoView>();
                foreach (PhotoView view in inPhotoList)
                {
                    int intCurrTechOrder = 0;
                    int intToTechOrder = 0;
                    NewInnerReturn inner = new NewInnerReturn();
                    inner.PhotoId = view.PhotoId;
                    inner.PicPath = view.picPath;
                    inner.Heigth = view.Heigth;
                    inner.Width = view.Width;
                    inner.PhotoAreas = view.Heigth * view.Width * 2.54 * 2.54 / 10000;
                    inner.OrderproductID = view.OrderProductId;
                    inner.Remark = inRemark;
                    List<WorkOrderFlowList> workFlowList = new List<WorkOrderFlowList>();
                    orderInfo order =
                        dataBase.orderInfo.Where(p => p.OrderProductId == view.OrderProductId).FirstOrDefault();
                    order.WorkOrderFlowList.Load();
                    //workFlowList = dataBase.WorkOrderFlowList.Where(p => p.orderInfo.OrderProductId == view.OrderProductId).ToList();
                    workFlowList = order.WorkOrderFlowList.ToList();
                    foreach (WorkOrderFlowList list in workFlowList)
                    {
                        list.tb_TechReference.Load();
                    }
                    WorkOrderFlowList currFlow = workFlowList.FirstOrDefault(p => p.Status == 1);
                    ///返单流程在委外或者工厂或者分堆，清除委外记录，格子记录，，委外单记录
                    currFlow.tb_TechReference.Load();
                    tb_Tech techCurr = currFlow.tb_Tech;
                    if (techCurr.TechType == 4 || techCurr.TechType == 5) //委外分堆节点
                    {
                        order.OutProcessRecord.Load();
                        OutProcessRecord outprocess = order.OutProcessRecord.FirstOrDefault();
                        if (outprocess != null)
                        {
                            dataBase.DeleteObject(outprocess); //删除委外记录
                        }
                        OutShopBillDetail outshopProduct =
                            dataBase.OutShopBillDetail.FirstOrDefault(p => p.OrderProductCode == order.OrderProductCode);
                        if (outshopProduct != null)
                        {
                            dataBase.DeleteObject(outshopProduct); //删除委外账单
                        }
                        GridRecord gridRecord = dataBase.GridRecord.FirstOrDefault(p => p.SomeId == order.OrderProductId);
                        if (gridRecord != null)
                        {
                            dataBase.DeleteObject(gridRecord); //删除分堆记录
                        }
                    }

                    if (currFlow != null)
                    {
                        intCurrTechOrder = currFlow.WorkOrder;
                    }
                    else
                    {
                        unSuccessList.Add(view);
                        continue;
                    }
                    WorkOrderFlowList toFlow = workFlowList.FirstOrDefault(p => p.tb_Tech.TechId == inReturnTechTo);
                    if (toFlow != null)
                    {
                        intToTechOrder = toFlow.WorkOrder;
                    }
                    else
                    {
                        unSuccessList.Add(view);
                        continue;
                    }
                    foreach (WorkOrderFlowList list in workFlowList)
                    {
                        list.tb_TechReference.Load();
                    }
                    WorkOrderFlowList printFlow =
                        workFlowList.FirstOrDefault(p => p.tb_Tech.TechType == (int)TechType.print);
                    if (printFlow == null)
                    {
                        unSuccessList.Add(view);
                        continue;
                    }
                    inner.ReturnTechFrom = workFlowList.FirstOrDefault(p => p.Status == 1).tb_Tech.TechId;
                    inner.ReturnTechTo = inReturnTechTo;
                    inner.ReturnUserId = inReturnUserId;
                    inner.CreateTime = DateTime.Now;
                    inner.CreateUserId = inCreateUserId;

                    photoInfo photo = dataBase.photoInfo.Where(p => p.photoId == view.PhotoId).FirstOrDefault();
                    //orderInfo order = dataBase.orderInfo.FirstOrDefault(p=>p.OrderProductId==view.OrderProductId);
                    ///修改流程
                    if (intCurrTechOrder >= intToTechOrder) //只把流程往前该
                    {
                        List<WorkOrderFlowList> workFlowUpdateList =
                            workFlowList.Where(p => p.WorkOrder <= intCurrTechOrder && p.WorkOrder > intToTechOrder).
                                ToList();
                        foreach (WorkOrderFlowList list in workFlowUpdateList)
                        {
                            list.Status = 0;
                            list.UserId = 0;

                        }
                        toFlow.Status = 1;
                    }

                    photo.status2 = (int)PhotoStatus2.innerReturn; //修改照片状态
                    if (toFlow.WorkOrder < printFlow.WorkOrder) //修改照片的状态
                    {
                        photo.status = (int)PhotoStatus.NoDistributePrinter;
                        photo.printerId = 0;
                    }
                    else
                    {
                        photo.status = (int)PhotoStatus.DistributedPrinter;
                    }
                    //修改流程状态
                    // if()
                    order.Priority = 12; //最高级别
                    dataBase.AddToNewInnerReturn(inner);
                    dataBase.SaveChanges();
                }
                return unSuccessList;
            }

        }
        /// <summary>
        /// 创建反单
        /// </summary>
        /// <param name="inPhotoList">照片列表</param>
        /// <param name="inReturnUserId">返工对象员工</param>
        /// <param name="CreateUserId">创建人</param>
        /// <param name="inRemark">返工原因</param>
        /// <param name="ReturnTechTo">返工到流程</param>
        public List<PhotoView> CreateInnerReturn(List<PhotoView> inPhotoList, out Dictionary<int, int> outPhotoDict)
        {
            using (newSampleYPDBEntities dataBase = new newSampleYPDBEntities())
            {


                List<PhotoView> unSuccessList = new List<PhotoView>();
                PaperWasteType style;
                Dictionary<int, PaperWasteRecords> photoWaste = new Dictionary<int, PaperWasteRecords>();
                Dictionary<int, int> outDict = new Dictionary<int, int>();
                foreach (PhotoView view in inPhotoList)
                {
                    int intCurrTechOrder = 0;
                    int intToTechOrder = 0;
                    NewInnerReturn inner = new NewInnerReturn();
                    inner.PhotoId = view.PhotoId;
                    inner.PicPath = view.picPath;
                    inner.Heigth = view.Heigth;
                    inner.Width = view.Width;
                    inner.PhotoAreas = view.Heigth * view.Width * 2.54 * 2.54 / 10000;
                    inner.OrderproductID = view.OrderProductId;
                    inner.Remark = view.Remark;
                    List<WorkOrderFlowList> workFlowList = new List<WorkOrderFlowList>();
                    orderInfo order =
                        dataBase.orderInfo.Where(p => p.OrderProductId == view.OrderProductId).FirstOrDefault();
                    order.WorkOrderFlowList.Load();
                    //workFlowList = dataBase.WorkOrderFlowList.Where(p => p.orderInfo.OrderProductId == view.OrderProductId).ToList();
                    workFlowList = order.WorkOrderFlowList.ToList();
                    foreach (WorkOrderFlowList list in workFlowList)
                    {
                        list.tb_TechReference.Load();
                    }
                    WorkOrderFlowList currFlow = workFlowList.FirstOrDefault(p => p.Status == 1);
                    ///返单流程在委外或者工厂或者分堆，清除委外记录，格子记录，，委外单记录
                    currFlow.tb_TechReference.Load();
                    tb_Tech techCurr = currFlow.tb_Tech;
                    if (techCurr.TechType == (int)TechType.OutProduct || techCurr.TechType == (int)TechType.PrintBill)
                    //委外分堆节点
                    {
                        order.OutProcessRecord.Load();
                        OutProcessRecord outprocess = order.OutProcessRecord.FirstOrDefault();
                        if (outprocess != null)
                        {
                            dataBase.DeleteObject(outprocess); //删除委外记录
                        }
                        OutShopBillDetail outshopProduct =
                            dataBase.OutShopBillDetail.FirstOrDefault(p => p.OrderProductCode == order.OrderProductCode);
                        if (outshopProduct != null)
                        {
                            dataBase.DeleteObject(outshopProduct); //删除委外账单
                        }
                        GridRecord gridRecord = dataBase.GridRecord.FirstOrDefault(p => p.SomeId == order.OrderProductId);
                        if (gridRecord != null)
                        {
                            dataBase.DeleteObject(gridRecord); //删除分堆记录
                        }
                    }

                    if (currFlow != null)
                    {
                        intCurrTechOrder = currFlow.WorkOrder;
                    }
                    else
                    {
                        view.Remark = "未有激活的流程";
                        unSuccessList.Add(view);
                        continue;
                    }
                    WorkOrderFlowList toFlow = workFlowList.FirstOrDefault(p => p.tb_Tech.TechId == view.TechTo.TechId);
                    if (toFlow != null)
                    {
                        intToTechOrder = toFlow.WorkOrder;
                    }
                    else
                    {
                        view.Remark = "返工到的流程不存在";
                        unSuccessList.Add(view);
                        continue;
                    }
                    foreach (WorkOrderFlowList list in workFlowList)
                    {
                        list.tb_TechReference.Load();
                    }
                    WorkOrderFlowList printFlow =
                        workFlowList.FirstOrDefault(
                            p =>
                            p.tb_Tech.TechType == (int)TechType.print || p.tb_Tech.TechType == (int)TechType.KuoYin || p.tb_Tech.TechType == (int)TechType.ExportPhoto);
                    if (printFlow == null)
                    {
                        view.Remark = "未找到打印流程";
                        unSuccessList.Add(view);
                        continue;
                    }
                    inner.ReturnTechFrom = view.TechFrom.TechId;
                    inner.ReturnTechTo = view.TechTo.TechId;
                    inner.ReturnUserId = view.DutyMan.UserID;
                    inner.CreateTime = DateTime.Now;
                    inner.CreateUserId = view.CreateMan.UserID;
                    inner.Remark = view.Remark;
                    photoInfo photo = dataBase.photoInfo.Where(p => p.photoId == view.PhotoId).FirstOrDefault();
                    //orderInfo order = dataBase.orderInfo.FirstOrDefault(p=>p.OrderProductId==view.OrderProductId);
                    ///修改流程
                    if (intCurrTechOrder >= intToTechOrder) //只把流程往前该
                    {
                        List<WorkOrderFlowList> workFlowUpdateList =
                            workFlowList.Where(p => p.WorkOrder <= intCurrTechOrder && p.WorkOrder > intToTechOrder).
                                ToList();
                        foreach (WorkOrderFlowList list in workFlowUpdateList)
                        {
                            list.Status = 0;
                            list.UserId = 0;

                        }
                        toFlow.Status = 1;
                    }

                    photo.status2 = (int)PhotoStatus2.innerReturn; //修改照片状态
                    photo.status = (int)PhotoStatus.NoDistributePrinter;
                    photo.printerId = 0;
                    //if (toFlow.WorkOrder < printFlow.WorkOrder)//修改照片的状态
                    //{
                    //    photo.status = (int)PhotoStatus.NoDistributePrinter;
                    //    photo.printerId = 0;
                    //}
                    //else
                    //{
                    //    photo.status = (int)PhotoStatus.DistributedPrinter;
                    //}
                    //修改流程状态
                    // if()
                    order.Priority = 12; //最高级别
                    style = dataBase.PaperWasteType.FirstOrDefault(p => p.PaperOperationTypeName == view.Remark);
                    if (style == null)
                    {
                        style = new PaperWasteType();
                        style.PaperOperationTypeName = view.Remark;
                        dataBase.AddToPaperWasteType(style);
                    }
                    dataBase.SaveChanges();

                    PaperWasteRecords records = new PaperWasteRecords();
                    records.Length = (view.Photo.Height * 2.54) / 100;
                    records.Width = (view.Photo.Width * 2.54) / 100;
                    records.PaperWasteType = style;
                    records.Remark = view.Remark;
                    records.Status = (int)WasterPaperStatus.unSure;
                    records.PrinterWaste = false;//是否机费
                    photo.picMakeUp.Load();
                    foreach (picMakeUp up in photo.picMakeUp)
                    {
                        up.BoardReference.Load();
                    }
                    List<picMakeUp> picMakeUpList = photo.picMakeUp.OrderByDescending(p => p.Board.BoardId).ToList();
                    List<Board> listBoard = new List<Board>();
                    foreach (picMakeUp up in picMakeUpList)
                    {
                        listBoard.Add(up.Board);
                    }
                    Board board = listBoard.OrderByDescending(p => p.lastPrintTime).FirstOrDefault();
                    if (board != null)
                    {
                        board.PaperInfoReference.Load();
                        records.PaperInfo = board.PaperInfo;
                    }
                    else
                    {
                        records.PaperInfo = dataBase.PaperInfo.First();
                    }

                    //records.PaperInfo = dataBase.PaperInfo.FirstOrDefault(p => p.PrintPaperId == board.PaperInfo.PrintPaperId);
                    photoWaste.Add(photo.photoId, records);
                    records.CreateTime = DateTime.Now;
                    dataBase.AddToNewInnerReturn(inner);
                    dataBase.SaveChanges();
                }
                //PaperWasteRecord_info info;
                foreach (KeyValuePair<int, PaperWasteRecords> pair in photoWaste)
                {
                    outDict.Add(pair.Key, pair.Value.Id);
                }
                outPhotoDict = outDict;
                return unSuccessList;
            }

        }
    }
}
